import React, { useEffect, useState } from 'react';
import { Cell } from './Cell';
import { useGameStore } from '../store/gameStore';

export const GameBoard: React.FC = () => {
  const { grid, gameStatus, difficulty, timeElapsed, initializeGame, revealCell, toggleFlag } = useGameStore();
  const [playerName, setPlayerName] = useState('');
  const [showSaveScore, setShowSaveScore] = useState(false);

  useEffect(() => {
    initializeGame(difficulty);
  }, [difficulty]);

  useEffect(() => {
    let timer: number;
    if (gameStatus === 'playing') {
      timer = setInterval(() => {
        useGameStore.setState({ timeElapsed: timeElapsed + 1 });
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [gameStatus, timeElapsed]);

  const handleSaveScore = async () => {
    if (!playerName.trim()) return;
    try {
      await useGameStore.getState().saveScore(playerName);
      setShowSaveScore(false);
      setPlayerName('');
    } catch (error) {
      console.error('Failed to save score:', error);
    }
  };

  return (
    <div className="flex flex-col items-center gap-4">
      <div className="flex gap-4 mb-4">
        <button
          onClick={() => initializeGame('easy')}
          className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
        >
          Easy
        </button>
        <button
          onClick={() => initializeGame('medium')}
          className="px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600"
        >
          Medium
        </button>
        <button
          onClick={() => initializeGame('hard')}
          className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
        >
          Hard
        </button>
      </div>

      <div className="mb-4">
        Time: {timeElapsed} seconds | Status: {gameStatus}
      </div>

      <div className="grid gap-px bg-gray-400 p-1">
        {grid.map((row, i) => (
          <div key={i} className="flex gap-px">
            {row.map((cell, j) => (
              <Cell
                key={`${i}-${j}`}
                cell={cell}
                onReveal={revealCell}
                onFlag={toggleFlag}
              />
            ))}
          </div>
        ))}
      </div>

      {gameStatus !== 'playing' && !showSaveScore && (
        <button
          onClick={() => setShowSaveScore(true)}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          Save Score
        </button>
      )}

      {showSaveScore && (
        <div className="flex gap-2">
          <input
            type="text"
            value={playerName}
            onChange={(e) => setPlayerName(e.target.value)}
            placeholder="Enter your name"
            className="px-4 py-2 border rounded"
          />
          <button
            onClick={handleSaveScore}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Submit
          </button>
        </div>
      )}
    </div>
  );
};